package com.zhoudy.demo;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentLinkedQueueTest {


   public static ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue();

    private static int threadCnt = 5;

   private static CountDownLatch countDownLatch = new CountDownLatch(threadCnt);

    public static void main(String[] args) throws InterruptedException {

        long timeStart = System.currentTimeMillis();

        ExecutorService es = Executors.newFixedThreadPool(4);

        //add
        ConcurrentLinkedQueueTest.offer();

        //submit works
        for (int i = 0; i < threadCnt; i++) {
            es.submit(new Poller());
        }
        countDownLatch.await();

        System.out.println("cost time " + (System.currentTimeMillis() - timeStart) + "ms");
        es.shutdown();

    }

    private static void offer() {
        for (int i = 0; i < 50; i++) {
            queue.offer(i);
        }
    }

    static  class Poller implements Runnable{

        @Override
        public void run() {
            while (!queue.isEmpty()){
                System.out.println(Thread.currentThread().getName()+":"+queue.poll());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            countDownLatch.countDown();
        }
    }
}
